`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    22:09:25 03/25/2014 
// Design Name: 
// Module Name:    enemy 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module enemy(clk,rand,new_enemy,position_x, position_y,position_valid);
input clk,new_enemy;//if an new enemy needs to be generated, the module will detect the posedge of the generation_require signal.
input [15:0] rand;
output reg [9:0] position_x, position_y;
output reg position_valid;//if the enemy is out of range, the signal will goes to 0.

reg [20:0] freq_count_x, freq_count_y;
reg x_clk;
reg y_clk;
reg x_clk_previous,new_enemy_previous;
reg y_clk_previous;

initial freq_count_x <= 0;
initial freq_count_y <= 0;
initial position_valid <= 1;
initial position_x <= 10'd560;
initial x_clk <= 0;
initial y_clk <= 0;
initial x_clk_previous=0;
initial new_enemy_previous=0;
initial y_clk_previous=0;

always @ (posedge clk)
begin
	x_clk_previous <= x_clk;
	if (freq_count_x == 1680000)//speed on the x_axis
	begin
		x_clk <= ~x_clk;
		freq_count_x <= 0;
	end
	else
		freq_count_x <= freq_count_x + 1;
	
	y_clk_previous <= y_clk;
	if (freq_count_y == 1680000)//speed on the y_axis
	begin
		y_clk <= ~y_clk;
		freq_count_y <= 0;
	end
	else
		freq_count_y <= freq_count_y + 1;
	
	new_enemy_previous <= new_enemy;
	if (new_enemy_previous == 0 & new_enemy == 1)
		position_x <= 10'd560;
	else
		if (x_clk_previous == 0 & x_clk == 1)
			position_x <= position_x - 1;
	
	if (new_enemy_previous == 0 & new_enemy == 1)
		position_y <= 100+rand[7:0];//initial y coordinates
	else
		if (y_clk_previous == 0 & y_clk == 1)
			if (rand[3] == 1)
				position_y <= position_y + rand[1:0];
			else
				position_y <= position_y - rand[1:0];
	
	if (position_x < 5 | position_y < 100 | position_y > 480)
		position_valid <= 0;
	else
		position_valid <= 1;
		
end
endmodule
